import React, { useState, useEffect, useRef } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { AtCountdown } from 'taro-ui';

import './index.scss';

/*
功能：页面滚动距离顶部超过设定值后显示返回顶部按钮，点击按钮滚动到页面顶部
@top: 设计图上图标距离顶部的距离
*/
const CountDown = ({ initTimes = 600, className = '', format, handleZero = null }) => {
  const [times, setTimes] = useState(initTimes);
  const startTime = useRef();

  useEffect(() => {
    startTime.current = new Date().getTime();
  }, []);

  useDidShow(() => {
    Taro.onAppShow(() => {
      let curTime = new Date().getTime();
      let theTimes = initTimes * 1000 - (curTime - startTime.current);
      times > 0 && setTimes(theTimes > 0 ? Math.floor(theTimes / 1000) : 0);
    });
  });

  return (
    <AtCountdown
      className={className}
      format={format}
      seconds={times}
      onTimeUp={() => handleZero && handleZero()}
      key={'AtCountdown_' + times}
    />
  );
};

export default CountDown;
